package com.nh.glory.ware.security.authentication.rest;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.nh.glory.core.constant.Constants;
import com.nh.glory.core.util.JsonMapper;
import com.nh.glory.ware.security.authentication.jwt.JwtFactory;
import com.nh.glory.ware.security.authentication.jwt.JwtToken;
import com.nh.glory.ware.security.model.LoginUserDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.WebAttributes;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
public class AjaxAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    private final ObjectMapper mapper = JsonMapper.INSTANCE.getMapper();
    private final JwtFactory jwtFactory;

    @Autowired
    public AjaxAuthenticationSuccessHandler(final JwtFactory tokenFactory) {
        this.jwtFactory = tokenFactory;
    }


    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException {
        LoginUserDetails principal = (LoginUserDetails) authentication.getPrincipal();
        JwtToken token = jwtFactory.createToken(principal);

        response.setStatus(HttpStatus.OK.value());
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        response.addHeader(Constants.AUTHORIZATION_HEADER, Constants.AUTHORIZATION_BEARER_PREFIX + token.getToken());
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put(Constants.TOKEN_KEY, token.getToken());
        tokenMap.put("username", principal.getUsername());

        mapper.writeValue(response.getWriter(), tokenMap);
        clearAuthenticationAttributes(request);
    }

    /**
     * Removes temporary authentication-related data which may have been stored
     * in the session during the authentication process..
     */
    private void clearAuthenticationAttributes(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session == null) {
            return;
        }
        session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
    }

}
